import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TaoBao {

    private static String webDriverPath = System.getProperty("user.dir") + File.separator + "program" + File.separator + "chromedriver.exe";
    private static WebDriver driver = null;
    private static String username = "您的账号";
    private static String password = "您的密码";
    private static Scanner sc = new Scanner(System.in);


    public static void main(String[] args) {
        System.out.println("请输入您的淘宝账号：");
        username = sc.nextLine().trim();
        System.out.println("请输入您的淘宝密码：");
        password = sc.nextLine().trim();
        start();
    }


    private static void start() {
        System.setProperty("webdriver.chrome.driver", webDriverPath);
        ChromeOptions options = new ChromeOptions();
        options.addArguments("Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        options.addArguments("Accept-Encoding=gzip, deflate, sdch");
        options.addArguments("Accept-Language=zh-CN,zh;q=0.8");
        options.addArguments("Connection=keep-alive");
        options.addArguments("Host=activityunion-marketing.meituan.com");
        options.addArguments("Upgrade-Insecure-Requests=1");
        options.addArguments("User-Agent=Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");
        try {
            if (Objects.isNull(driver)) {
                driver = new ChromeDriver(options);
                userLogin(driver);
            }
            shopping(driver);
            System.out.println("请选择两种方式：");
            System.out.println("输入1表示让程序疯狂抢购，直到购买成功为止！");
            System.out.println("输入2表示，指定时间点去抢购，之后程序会疯狂抢，直到购买成功为止！");
            String code = sc.nextLine().trim();
            String timeStr = null;
            while (true) {
                //下一步 结算购物车
                if ("1".equals(code)) {
                    System.out.println("直接开始疯狂抢购！");
                    buy();
                }

                if ("2".equals(code)) {
                    if (null == timeStr) {
                        System.out.println("输入日期格式：例如：2020-08-25 05:20:00");
                        timeStr = sc.nextLine().trim();
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = sdf.parse(timeStr);
                    while (date.after(new Date())) {
                        Thread.sleep(10);
                    }
                    //到时间了，开始疯狂抢购！
                    System.out.println("时间到！开始疯狂抢购！");
                    buy();
                }
                shopping(driver);


            }
            //最后关闭程序
            //driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!Objects.isNull(driver)) {
                driver.close();
            }
        }

    }


    /**
     * 全选商品并提交订单
     */
    private static void buy() {
        long start = System.currentTimeMillis();
        try {
            //勾选全部
            driver.findElement(By.xpath("//*[@id=\"J_SelectAll2\"]/div[1]/label")).click();
            System.out.println("勾选成功");
            Thread.sleep(100);
            //购买
            driver.findElement(By.id("J_Go")).click();
            System.out.println("结算成功");
            Thread.sleep(200);
            //使用默认地址，确认购买
            driver.findElement(By.className("go-btn")).click();
            System.out.println("提交成功");
            Thread.sleep(200);
            long end = System.currentTimeMillis();
            System.out.println("购买成功，耗时：" + (end - start) + "ms");
        } catch (Exception ignored) {
            long end = System.currentTimeMillis();
            System.out.println("购买尚未成功，耗时：" + (end - start) + "ms");
        }
    }


    /**
     * 登录
     */
    private static void userLogin(WebDriver driver) throws Exception {
        String mobileUrl = "https://login.m.taobao.com/login.htm";
        driver.get(mobileUrl);
        Thread.sleep(200);//等待0.2秒
        WebElement usernameWebElement = driver.findElement(By.id("fm-login-id"));
        usernameWebElement.sendKeys(username);
        WebElement passwordWebElement = driver.findElement(By.id("fm-login-password"));
        passwordWebElement.sendKeys(password);
        //模拟滑动
        Thread.sleep(1000);
        WebElement draggable = driver.findElement(By.id("nc_1_n1z"));//定位元素
        Actions bu = new Actions(driver); // 声明action对象
        bu.clickAndHold(draggable).build().perform(); // clickAndHold鼠标左键按下draggable元素不放
        bu.moveByOffset(380, 2).perform(); // 平行移动鼠标
        Thread.sleep(500);
        bu.moveByOffset(500, 2).perform(); // 平行移动鼠标
        Thread.sleep(500);
        //bu.moveByOffset(420, 2).perform(); // 平行移动鼠标
        //Thread.sleep(1500);
        WebElement btnWebElement = driver.findElement(By.xpath("//button[@class='fm-button fm-submit password-login']"));
        btnWebElement.click();
        //等待30s，有些用户可能设置短信认证，，让管理手动处理吧
        //Thread.sleep(30000);
        //先测试
        Thread.sleep(1000);
    }

    /**
     * 访问购物车
     */
    private static void shopping(WebDriver driver) throws InterruptedException {
        //打开淘宝主页
        driver.get("https://cart.taobao.com/cart.htm");
        Thread.sleep(1000);
        //购物车按钮
        //driver.findElement(By.id("mc-menu-hd")).click();
        //Thread.sleep(500);
    }


}
